package com.ebelter.bodyfatscale.ui.pager.main;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.ebelter.bodyfatscale.R;
import com.ebelter.bodyfatscale.adapter.TrendHLvAdapter;
import com.ebelter.bodyfatscale.common.AppDateLitConstants;
import com.ebelter.bodyfatscale.common.Constants;
import com.ebelter.bodyfatscale.moudules.https.NetUtils;
import com.ebelter.bodyfatscale.moudules.https.interfaces.HttpResponse;
import com.ebelter.bodyfatscale.moudules.https.response.GetAverageResponse;
import com.ebelter.bodyfatscale.moudules.https.response.HttpsParameters;
import com.ebelter.bodyfatscale.ui.activity.HistoryListActivity;
import com.ebelter.bodyfatscale.ui.view.EndlessRecyclerOnScrollListener;
import com.ebelter.bodyfatscale.ui.view.HoriLineView;
import com.ebelter.bodyfatscale.ui.view.combinviews.CombinView1;
import com.ebelter.bodyfatscale.util.NumUtils;
import com.ebelter.bodyfatscale.util.ScaleBaseUtils;
import com.ebelter.bodyfatscale.util.StringUtils;
import com.ebelter.bodyfatscale.util.ToastUtil;
import com.ebelter.bodyfatscale.util.UserSpUtil;
import com.ebelter.bodyfatscale.util.ViewUtils;
import com.ebelter.btlibrary.util.ULog;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
public class TrendsPager extends BasePagerMain implements RadioGroup.OnCheckedChangeListener {


    private static final String TAG = "TrendsPager";
    private long lastLoadMoreTime;
    private boolean isLoadingData;

    public static final int TYPE_WEIGHT = 1;
    public static final int TYPE_BODYFAT = 2;
    public static final int TYPE_MUSCLE = 3;

    public static final int TIME_DAY = 4;
    public static final int TIME_WEEK = 5;
    public static final int TIME_MONTH = 6;

    private String avg_weight_day;
    private String avg_weight_week;
    private String avg_weight_month;
    private String avg_bfp_day;
    private String avg_bfp_week;
    private String avg_bfp_month;
    private String avg_mass_day;
    private String avg_mass_week;
    private String avg_mass_month;
    private String change_weight;
    private String change_bodyfat_percentage;
    private String change_muscle_mass;

    private String unitKg = StringUtils.getResStr(R.string.kg);
    private String unitLb = StringUtils.getResStr(R.string.lb);

    private void getStrs(){
        avg_weight_day=StringUtils.getResStr(R.string.avg_weight_day);
        avg_weight_week=StringUtils.getResStr(R.string.avg_weight_week);
        avg_weight_month=StringUtils.getResStr(R.string.avg_weight_month);
        avg_bfp_day=StringUtils.getResStr(R.string.avg_bfp_day);
        avg_bfp_week=StringUtils.getResStr(R.string.avg_bfp_week);
        avg_bfp_month=StringUtils.getResStr(R.string.avg_bfp_month);
        avg_mass_day=StringUtils.getResStr(R.string.avg_mass_day);
        avg_mass_week=StringUtils.getResStr(R.string.avg_mass_week);
        avg_mass_month=StringUtils.getResStr(R.string.avg_mass_month);
        change_weight=StringUtils.getResStr(R.string.change_weight);
        change_bodyfat_percentage=StringUtils.getResStr(R.string.change_bodyfat_percentage);
        change_muscle_mass=StringUtils.getResStr(R.string.change_muscle_mass);
    }


    private int currentDisplayType;
    private int currentDisplayTime;


    @BindView(R.id.trend_gongneng_rg)
    RadioGroup trend_gongneng_rg;

    @BindView(R.id.trend_time_rg)
    RadioGroup trend_time_rg;

//    @BindView(R.id.trend_chartView)
//    ChartView trend_chartView;

    @BindView(R.id.trend_time_left_iv)
    ImageView trend_time_left_iv;

    @BindView(R.id.trend_time_tv)
    TextView trend_time_tv;

    @BindView(R.id.trend_time_right_iv)
    ImageView trend_time_right_iv;

    @BindView(R.id.trend_unit_time_tv)
    TextView trend_unit_time_tv;

    @BindView(R.id.trend_avg_weight_cb1)
    CombinView1 trend_avg_weight_cb1;

    @BindView(R.id.trend_change_weight_cb1)
    CombinView1 trend_change_weight_cb1;


    //历史记录
    @BindView(R.id.trends_topright_iv)
    ImageView trends_topright_iv;


    @BindView(R.id.horlineview)
    HoriLineView horiLineView;

    @BindView(R.id.trend_hlv)
    RecyclerView trend_hlv;
    private TrendHLvAdapter trendHLvAdapter;




    private String unit_p1;
    private String unit_p2;

    public TrendsPager(Activity context) {
        super(context);
    }

    @Override
    protected int loadLayoutById() {
        return R.layout.pager_trends;
    }

    @Override
    public void initViews() {
        getStrs();

        initCharView();
        setListeners();
        horiLineView.setDisplay(true);//设置横线为可以显示
        ViewUtils.displayView(horiLineView);
        currentDisplayType = TYPE_WEIGHT;
        currentDisplayTime = TIME_DAY;
        unit_p1 = Constants.isKgUnit?StringUtils.getResStr(R.string.kg):StringUtils.getResStr(R.string.lb);
        unit_p2 = StringUtils.getResStr(R.string.day);
        disPlayUnit();
        DAY_START_INDEX=0;
        WEEK_START_INDEX=0;
        MONTH_START_INDEX=0;
        setTrendHLvAdapterDisPlayStyle();
        requestDisplayData(true,false);

        trends_topright_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openHistoryDatas();
            }
        });
    }



    //打开历史记录数据
   // boolean bb;
    private void openHistoryDatas() {
        Intent intent=new Intent(getActivity(), HistoryListActivity.class);
        getActivity().startActivityForResult(intent,HistoryListActivity.REQUEST_CODE);
    }




    private void setListeners() {
        trend_gongneng_rg.setOnCheckedChangeListener(this);
        trend_time_rg.setOnCheckedChangeListener(this);


       // 设置加载更多监听
        trend_hlv.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore(boolean isSlidingToLeft) {
                // 加载更多
                ULog.e(TAG,"-----onLoadMore() isSlidingToLeft="+isSlidingToLeft);
                if (!isSlidingToLeft){
                    requestDisplayData(false,false);
                }
            }
        });

    }

    private void initCharView() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        trend_hlv.setLayoutManager(linearLayoutManager);


        trendHLvAdapter=new TrendHLvAdapter(getActivity());
        trend_hlv.setAdapter(trendHLvAdapter);


    }

    @Override
    public void initData(Object data) {

    }

    @Override
    public void switchUnitUpdate() {
        updateCb1Title1();
        if (currentDisplayType==TYPE_WEIGHT||currentDisplayType==TYPE_MUSCLE){
            unit_p1=Constants.isKgUnit?unitKg:unitLb;
        }else if (currentDisplayType==TYPE_BODYFAT){
            unit_p1="%";
        }
        disPlayUnit();
        displayTargetWeightLine();
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        switch (checkedId){
                case R.id.gnrg_weight:
                    currentDisplayType=TYPE_WEIGHT;
                    unit_p1 = Constants.isKgUnit?unitKg:unitLb;
                    ViewUtils.displayView(horiLineView);
                    displayTargetWeightLine();
                    break;
                case R.id.gnrg_bodyfat:
                    currentDisplayType=TYPE_BODYFAT;
                    unit_p1 = StringUtils.getResStr(R.string.p);
                    ViewUtils.hideView(horiLineView);
                    break;
                case R.id.gnrg_musclemass:
                    currentDisplayType=TYPE_MUSCLE;
                    unit_p1 =Constants.isKgUnit?unitKg:unitLb;
                    ViewUtils.hideView(horiLineView);
                    break;
                case R.id.trg_day:
                    currentDisplayTime=TIME_DAY;
                    unit_p2 = StringUtils.getResStr(R.string.day);
                    break;
                case R.id.trg_week:
                    currentDisplayTime=TIME_WEEK;
                    unit_p2 = StringUtils.getResStr(R.string.week);
                    break;
                case R.id.trg_month:
                    currentDisplayTime=TIME_MONTH;
                    unit_p2 = StringUtils.getResStr(R.string.month);
                    break;
        }
        setTrendHLvAdapterDisPlayStyle();//设置Adapter的显示类型
        disPlayUnit();//显示单位
        updateCb1Title1();//更新组合控件1
        if (trend_gongneng_rg==group){
            switchDisplayData();
        }else if (trend_time_rg==group){//说明点击的是时间控件了
            ULog.i(TAG,"点击了时间控件Rg");
            requestDisplayData(true,true);
        }

    }



    //更新title1
    private void updateCb1Title1() {
        String title11="";
        String title21="";
        String title12="";
        String title22="";
        String title13="";

        if (currentDisplayTime==TIME_DAY){
            switch (currentDisplayType){
                case TYPE_WEIGHT:
                    title11=avg_weight_day;
                    title21=change_weight;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat(trendHLvAdapter.getAvg(TIME_DAY,TYPE_WEIGHT)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_DAY,TYPE_WEIGHT),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;;
                    break;
                case TYPE_BODYFAT:
                    title11=avg_bfp_day;
                    title21=change_bodyfat_percentage;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei( trendHLvAdapter.getAvg(TIME_DAY,TYPE_BODYFAT),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_DAY,TYPE_BODYFAT),1)+"":"";
                    title13="%";
                    break;
                case TYPE_MUSCLE:
                    title11=avg_mass_day;
                    title21=StringUtils.getResStr(R.string.change_muscle_mass);
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat(trendHLvAdapter.getAvg(TIME_DAY,TYPE_MUSCLE)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_DAY,TYPE_MUSCLE),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
            }

        }else if (currentDisplayTime==TIME_WEEK){
            switch (currentDisplayType){
                case TYPE_WEIGHT:
                    title11=avg_weight_week;
                    title21=change_weight;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat(trendHLvAdapter.getAvg(TIME_WEEK,TYPE_WEIGHT)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_WEEK,TYPE_WEIGHT),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
                case TYPE_BODYFAT:
                    title11=avg_bfp_week;
                    title21=change_bodyfat_percentage;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getAvg(TIME_WEEK,TYPE_BODYFAT),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei( trendHLvAdapter.getChange(TIME_WEEK,TYPE_BODYFAT),1)+"":"";
                    title13="%";
                    break;
                case TYPE_MUSCLE:
                    title11=avg_mass_week;
                    title21=change_muscle_mass;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat((float) trendHLvAdapter.getAvg(TIME_WEEK,TYPE_MUSCLE)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei( trendHLvAdapter.getChange(TIME_WEEK,TYPE_MUSCLE),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;;
                    break;
            }

        }else if(currentDisplayTime==TIME_MONTH){
            switch (currentDisplayType){
                case TYPE_WEIGHT:
                    title11=avg_weight_month;
                    title21=change_weight;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat( trendHLvAdapter.getAvg(TIME_MONTH,TYPE_WEIGHT)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei( trendHLvAdapter.getChange(TIME_MONTH,TYPE_WEIGHT),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
                case TYPE_BODYFAT:
                    title11=avg_bfp_month;
                    title21=change_bodyfat_percentage;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getAvg(TIME_MONTH,TYPE_BODYFAT),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_MONTH,TYPE_BODYFAT),1)+"":"";
                    title13="%";
                    break;
                case TYPE_MUSCLE:
                    title11=avg_mass_month;
                    title21=change_muscle_mass;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat( trendHLvAdapter.getAvg(TIME_MONTH,TYPE_MUSCLE)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_MONTH,TYPE_MUSCLE),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
            }

        }

        if (trend_avg_weight_cb1!=null){
            trend_avg_weight_cb1.setTitle1(title11);
            trend_avg_weight_cb1.setTitle2(title12);
            trend_avg_weight_cb1.setTitle3(title13);
        }
        if (trend_change_weight_cb1!=null){
            trend_change_weight_cb1.setTitle1(title21);
            trend_change_weight_cb1.setTitle2(title22);
            trend_change_weight_cb1.setTitle3(title13);
        }

    }

    //显示体重
    private void disPlayUnit(){
        if (trend_unit_time_tv!=null){
            trend_unit_time_tv.setText(unit_p1);
        }
    }

    private int DAY_START_INDEX;
    private int WEEK_START_INDEX;
    private int MONTH_START_INDEX;


    public void requestDisplayData(final boolean scroll2end,boolean isFrom0) {
//        if (System.currentTimeMillis()-lastLoadMoreTime<30){
//            ULog.i(TAG,"请求数据小于30毫秒秒被拒绝的掉");
//            return;
//        }
        lastLoadMoreTime=System.currentTimeMillis();
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }
        if (isLoadingData){
            ULog.i(TAG,"正在加载数据，此次请求拒绝掉");
            return;
        }



        if (isFrom0){

            DAY_START_INDEX=0;

            WEEK_START_INDEX=0;

            MONTH_START_INDEX=0;

            if (trendHLvAdapter!=null){
                trendHLvAdapter.clearData();
            }

        }

        ULog.i(TAG, "-------requestDisplayData()------currentDisplayTime = "+currentDisplayTime+"-------currentDisplayType = "+currentDisplayType);
        final int whichTime;
        final int start_index;
        if (currentDisplayTime==TIME_DAY){
            whichTime=1;
            start_index=DAY_START_INDEX;
        }else if (currentDisplayTime==TIME_WEEK){
            whichTime=2;
            start_index=WEEK_START_INDEX;
        }else if (currentDisplayTime==TIME_MONTH){
            whichTime=3;
            start_index=MONTH_START_INDEX;
        }else {
            return;
        }
        isLoadingData=true;

        ULog.i(TAG, "-------currentDisplayTime2 = "+currentDisplayTime+"-------currentDisplayType = "+currentDisplayType);
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put(HttpsParameters.USER_ID, UserSpUtil.readLong(Constants.IUser.USER_ID));
        paramMap.put(HttpsParameters.START_INDEX, start_index);
       // paramMap.put(HttpsParameters.PAGE_SIZE, AppDateLitConstants.PAGE_SIZE);
        paramMap.put(HttpsParameters.PAGE_SIZE, AppDateLitConstants.PAGE_SIZE);

        NetUtils.getInstance().getsAverageData(this, whichTime, paramMap, new HttpResponse<GetAverageResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, GetAverageResponse getAverageResponse) {
                ULog.i(TAG,"---------------start_index="+start_index);
              //  SystemClock.sleep(3000);
                if (isRequestSuccess){
                    if (getAverageResponse.resultCode==0){
                        ULog.i(TAG,"---------------getsAverageData请求成功--------------"+getAverageResponse);
                        if (getAverageResponse.getResultData()!=null&&getAverageResponse.getResultData().getData()!=null&&getAverageResponse.getResultData().getData().size()>0){
                            ULog.i(TAG,"---------------getsAverageData请求成功--------------whichTime="+whichTime+"--" +
                                    "-DAY_START_INDEX="+DAY_START_INDEX+"----WEEK_START_INDEX="+WEEK_START_INDEX+"----MONTH_START_INDEX="+MONTH_START_INDEX);
                            if (getAverageResponse.getResultData()!=null&&getAverageResponse.getResultData().getData()!=null&&getAverageResponse.getResultData().getData().size()>0){
                                if (whichTime==1){
                                    DAY_START_INDEX++;
                                }else if (whichTime==2){
                                    WEEK_START_INDEX++;
                                }else if (whichTime==3){
                                    MONTH_START_INDEX++;
                                }
                            }

                            displayData(getAverageResponse.getResultData(),whichTime,scroll2end);
                        }

                    }else {
                        ULog.i(TAG,"---------------getsAverageData请求失败-------原因-----"+getAverageResponse.resultMessage);
                    }
                }else {
                    ULog.i(TAG,"---------------getsAverageData请求失败--------------");
                }
                isLoadingData=false;
            }
        });


    }

    private void setTrendHLvAdapterDisPlayStyle(){
        if (trendHLvAdapter!=null){
            trendHLvAdapter.setCurrentDisplayType(currentDisplayType);
            trendHLvAdapter.setCurrentDisplayTimeType(currentDisplayTime);
        }
    }



    //显示数据 whichTime 1DAY 2WEEK 3MONTH
    private void displayData(final GetAverageResponse.ResultDataBean resultData,int whichTime,final boolean scroll2end) {
        ULog.i(TAG,"---displayData---A--whichTime="+whichTime);
        if (resultData==null){
            return;
        }
        if (trendHLvAdapter!=null){
            trendHLvAdapter.addDatas(resultData.getData(),whichTime);
            if (scroll2end){
                ViewUtils.recyclerViewScrollToPosition(trend_hlv,trendHLvAdapter.getItemCount()-1);
            }
            displayTargetWeightLine();
            updateCb1Title1();
        }
    }


    //显示目标体重横线
    public void displayTargetWeightLine(){
        ULog.i(TAG,"---displayTargetWeightLine---A");
        if (horiLineView==null){
            return;
        }
        ULog.i(TAG,"---displayTargetWeightLine---B");
        if (trendHLvAdapter!=null&&trendHLvAdapter.getItemCount()!=0){
            ULog.i(TAG,"---displayTargetWeightLine---C");
            horiLineView.setDisplay(true);
            float p=0;
            String displayText="";
            trendHLvAdapter.calculator();//计算一遍的意思
            if (trendHLvAdapter.maxWeight<=0){
                    p=0;
            }else {
                    float targetWeight=UserSpUtil.readFloat(Constants.IUser.TARGET_WEIGHT);
                    p= targetWeight/trendHLvAdapter.maxWeight;
                    displayText=NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat(targetWeight),1)+"";
            }
            ULog.i(TAG,"---displayTargetWeightLine---D--p="+p+"---displayText="+displayText);
            horiLineView.setPercentage(p);
            if (p==0){
                horiLineView.setDisplay(false);
            }
            horiLineView.setDisplayText(displayText);
        }else {
            horiLineView.setDisplay(false);
        }
        horiLineView.show();
    }




//    //显示平均组合控件1
//    private void displayAvgCB1(String title1,String title2,String title3){
//        if (trend_avg_weight_cb1==null)return;
//        trend_avg_weight_cb1.setTitle1(title1);
//        trend_avg_weight_cb1.setTitle1(title2);
//        trend_avg_weight_cb1.setTitle1(title3);
//    }

//    //显示变化组合控件2
//    private void displayChangeCB2(String title1,String title2,String title3){
//        if (trend_change_weight_cb1==null)return;
//        trend_change_weight_cb1.setTitle1(title1);
//        trend_change_weight_cb1.setTitle1(title2);
//        trend_change_weight_cb1.setTitle1(title3);
//    }

    private void switchDisplayData() {
        ULog.i(TAG, "-------switchDisplayData()-------");
        ULog.i(TAG, "-------currentDisplayTime = "+currentDisplayTime+"-------currentDisplayType = "+currentDisplayType);

    }
}
